package com.chu.cloud.service.impl;

import com.chu.cloud.entity.User;
import com.chu.cloud.entity.UserPoint;
import com.chu.cloud.enums.PointActionEnums;
import com.chu.cloud.enums.UserGradeEnum;
import com.chu.cloud.repository.UserPointRepository;
import com.chu.cloud.repository.UserRepository;
import com.chu.cloud.stream.payload.OrderPaySuccessDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/8/28 10:37
 * @Description:
 */
@Service
public class PointService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserPointRepository pointRepository;

    public void rewardPoint(OrderPaySuccessDto payLoad) {
        UserPoint userPoint = new UserPoint();
        userPoint.setAction(PointActionEnums.REWARD);
        userPoint.setLockForOrderId(payLoad.getOrderNo());
        userPoint.setMemberId(payLoad.getMemberId());
        userPoint.setPoint(payLoad.getRewardPoint());
        UserPoint point = pointRepository.save(userPoint);
        Integer rewardPoint = pointRepository.findPoint(point.getMemberId(), PointActionEnums.REWARD);
        Integer consumerPoint = pointRepository.findPoint(point.getMemberId(), PointActionEnums.CONSUME);
        User user = userRepository.findOne(point.getMemberId());
        UserGradeEnum gradeEnum = user.getGrade();
        user.setGrade(gradeEnum.nextGrade(gradeEnum,(rewardPoint - consumerPoint)));
        userRepository.save(user);

    }
}
